import {Component, Input, OnDestroy, OnInit} from '@angular/core';
import {ApiService} from "@core/services/http/api.service";
import {ApesMessageService} from "@shared/apes/message";
import {DatePipe} from "@angular/common";

@Component({
  selector: 'pro-panel',
  templateUrl: './pro-panel.component.html',
  styleUrls: ['./pro-panel.component.scss']
})
export class ProPanelComponent implements OnInit, OnDestroy {
  @Input()
  set parmas(value: any) {
    this._parmas = value;
  }

  get parmas() {
    return this._parmas;
  }

  _parmas: any;

  rowList = {};
  jjcdhNum: any;
  cphm: any;
  mdid: any;
  rowData = [];
  pageRowIndex: number = 0;
  pageColIndex: number = 0;
  private timer;
  hide = 'none';
  tableData = [];
  hiden = 'none';
  infotable = [];
  comeNum: string;
  waitList: any[] = [];
  afterList: any[] = [];
  tabData = [];

  constructor(private apiService: ApiService,
              private msg: ApesMessageService,
              private datePipe: DatePipe,) {
  }

  ngOnInit() {
    let times = (1000 * 10);
    this.timer = setInterval(() => {
      if (this.rowList['projectRemark'] !== undefined) {
        this.rowData = this.pageRow(this.rowList['projectRemark'], 2);
      }
      if(this.rowList['nodeItem'] !== undefined) {
        this.rowData = this.pageRow(this.rowList['nodeItem'], 3);
      }
      if(this.rowList['mx'] !== undefined) {
        this.tableData = this.pageCol(this.rowList['mx'], 3);
      }
      if(this.rowList['array'] !== undefined) {
        this.tableData = this.pageCol(this.rowList['array'], 3);
      }
    }, times);
  }

  getFun(key: string, cphm: string, mdid: string) {
    this.rowData = [];
    this.rowList = {};
    this.jjcdhNum = key;
    this.cphm = cphm;
    this.mdid = mdid;
    this.getPanel();
  }

  change() {
    if (this.hide === 'none') {
      this.hide = 'block';
      this.getTable();
    } else {
      this.hide = 'none';
    }
  }

  tabChanges($event) {
    this.comeNum = $event;
    this.tableData = this.tableData.map( item => {
      if(this.comeNum === item.LYDJHM) {
        if(item.cilck !== true) {
          this.hiden = 'block';
          this.getInfo($event);
          return {...item, cilck: true};
        }else {
          this.hiden = 'none';
          return {...item, cilck: false};
        }
      }else {
        return {...item, cilck: false};
      }
    })
  }

  getPanel() {
    if (this.parmas["api"]) {
      let data = {
        'interfaceMethod': this.parmas["api"],
        'pdata': {'JJCDH': this.jjcdhNum, 'CPHM': this.cphm, 'MDID': this.mdid}
      };
      this.apiService.post('report.interface', {'body': JSON.stringify(data)}).subscribe(
        (resultData) => {
          const result = JSON.parse(resultData);
          if (result.success) {
            if (result.obj.length !== 0) {
              const data = JSON.parse(result.obj);
              this.afterList = [];
              this.waitList = [];
              if (data['MX'] !== undefined) {
                let itemData: any[] = data['MX'];
                for(let item of itemData) {
                  if(item['innerBJ'] === 1) {
                    this.afterList.push(item);
                  }else {
                    this.waitList.push(item);
                  }
                }
              }
              this.rowList = data;
              if (this.rowList['projectRemark']) {
                this.rowList['projectRemark'] = this.rowList['projectRemark'].sort(this.sortarr('SJ', 'down'));
              }
              if (this.rowList['projectRemark'] !== undefined) {
                this.rowData = this.pageRow(this.rowList['projectRemark'], 2);
              }
              if(this.rowList['nodeItem'] !== undefined) {
                this.rowData = this.pageRow(this.rowList['nodeItem'], 3);
              }
              if(this.rowList['mx'] !== undefined) {
                this.tableData = this.pageCol(this.rowList['mx'], 3);
              }
              if(this.rowList['array'] !== undefined) {
                this.tableData = this.pageCol(this.rowList['array'], 3);
              }
            }
          } else {
            this.msg.info(result.msg);
          }
        });
    }
  }

  getTable() {
    if (this.parmas["tableApi"]) {
      let data = {
        'interfaceMethod': this.parmas["tableApi"],
        'pdata': {'JJCDH': this.jjcdhNum, 'CPHM': this.cphm, 'MDID': this.mdid}
      };
      this.apiService.post('report.interface', {'body': JSON.stringify(data)}).subscribe(
        (resultData) => {
          const result = JSON.parse(resultData);
          if (result.success) {
            if (result.obj.length !== 0) {
              const data = JSON.parse(result.obj);
              let list = data.sort(this.sortarr('SJ', 'down'));
              this.tableData = list.map(item => {
                return {...item, cilck: false};
              });
              if (data.length <= 0) this.msg.error('暂无数据！');
            }
          } else {
            this.msg.info(result.msg);
          }
        });
    }
  }

  getInfo(num: string) {
    if (this.parmas["infoApi"]) {
      let data = {'interfaceMethod': this.parmas["infoApi"], ' pdata': {'LYDJHM': num}};
      this.apiService.post('report.interface', {'body': JSON.stringify(data)}).subscribe(
        (resultData) => {
          const result = JSON.parse(resultData);
          if (result.success) {
            if (result.obj.length !== 0) {
              const data = JSON.parse(result.obj);
              this.infotable = data;
              if (data.length <= 0) this.msg.error('暂无数据！');
            }
          } else {
            this.msg.info(result.msg);
          }
        });
    }
  }

  //显示时间 天/小时   小时/分钟  分钟
  toHour(minutes) {
    if (Math.floor(minutes / 60 / 24) >= 1) {
      if(Math.floor(minutes / 60 % 24) < 1) {
        return (Math.floor(minutes / 60 / 24) + '天');
      }else {
        return (Math.floor(minutes / 60 / 24) + '天' + Math.floor(minutes / 60 % 24) + '时');
      }
    } else if (Math.floor(minutes / 60 / 24) < 1) {
      if (Math.floor(minutes) < 60) {
        return (Math.floor(minutes % 60) + '分');
      }
      if(Math.floor(minutes % 60) < 1) {
        return (Math.floor(minutes / 60) + '时')
      }else {
        return (Math.floor(minutes / 60) + '时' +  Math.floor(minutes % 60) + '分');
      }
    }
  }

  // 时间戳转换 月-日 时：分
  timeChange(time: number) {
    let day;
    if(time !== undefined) {
      day = this.datePipe.transform(new Date(time),
        'yyyy-MM-dd HH:mm:ss').slice(5, 16);
      return day;
    }
  }

  // 排序 倒序
  sortarr(key, order) {
    return function(a, b) {
      a[key] == undefined ? a[key] = 0 :
        b[key] == undefined ? b[key] = 0 : 0;
      if (order == 'up') {
        return a[key] - b[key];
      } else if (order == 'down') {
        return b[key] - a[key];
      }
    };
  }

  //  分页
  pageRow(arrData: any, page: number) {
    let rowData = [];
    const count = arrData.length;
    let tempIndex = 0;
    for (let i = this.pageRowIndex; i < count; i++) {
      if (tempIndex < page) {
        rowData.push(arrData[i]);
      } else {
        break;
      }
      tempIndex++;
      this.pageRowIndex++;
    }
    //当数据遍历完 重新请求数据
    if (this.pageRowIndex >= count) {
      this.pageRowIndex = 0;
    }
    return rowData;
  }

  pageCol(arrData: any, page: number) {
    let rowData = [];
    const count = arrData.length;
    let tempIndex = 0;
    for (let i = this.pageColIndex; i < count; i++) {
      if (tempIndex < page) {
        rowData.push(arrData[i]);
      } else {
        break;
      }
      tempIndex++;
      this.pageColIndex++;
    }
    //当数据遍历完 重新请求数据
    if (this.pageColIndex >= count) {
      this.pageColIndex = 0;
    }
    return rowData;
  }

  yhgzHead = [
    { lable: "", style: "20px" },
    { lable: "配件数", style: "70px" },
    { lable: "要货时间", style: "110px" },
    { lable: "耗时", style: "100px" },
    { lable: "到店时间", style: "170px" }
  ];

  nxddHead = [
    { lable: "内协基地", style: "160px" },
    { lable: "交车耗时", style: "115px" },
    { lable: "内协耗时", style: "115px" },
    { lable: "还车耗时", style: "115px" }
  ];

  dsbjHead = [
    { lable: "", style: "20px" },
    { lable: "开始评估", style: "110px" },
    { lable: "开始时间", style: "110px" },
    { lable: "方案完成", style: "110px" },
    { lable: "核损完成", style: "160px" },
    // { lable: "耗时", style: "80px" }
  ];

  ngOnDestroy() {
    if (this.timer) {
      clearInterval(this.timer);
    }
  }

}
